package com.rz.htk.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.htk.product.entity.ProductDiscount;
import com.rz.htk.product.entity.ProductPrice;
import com.rz.htk.product.entity.vo.PrdDiscountParam;
import com.rz.htk.product.mapper.ProductDiscountMapper;
import com.rz.htk.product.service.IProductDiscountService;
import com.rz.htk.product.service.IProductPriceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ProductDiscountServiceImpl
 * @Description 产品资费折扣信息
 * @Author maweiyue
 * @Date 2019/5/13 19:20
 */
@Service
public class ProductDiscountServiceImpl extends ServiceImpl<ProductDiscountMapper, ProductDiscount> implements IProductDiscountService {

    @Resource
    private IProductPriceService productPriceService;

    /**
     * 根据代理商id和产品线路id获取折扣信息
     * @param mngId 代理商id
     * @param priceId 产品线路id
     * @return
     */
    @Override
    public ProductDiscount getProductDiscount(Integer mngId, Integer priceId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("price_id", priceId);
        queryWrapper.eq("mng_id", mngId);
        List<ProductDiscount> list = list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 获取指定产品针对某代理商的折扣列表
     * @param prdCode 产品编号
     * @param mngId 代理商id
     * @return
     */
    @Override
    public List<ProductDiscount> listProductDiscount(String prdCode, Integer mngId) {
        List<ProductPrice> priceList = productPriceService.listProductPriceByPrdcode(prdCode);
        if (CollectionUtils.isNotEmpty(priceList)) {
            List<Integer> priceIdList = new ArrayList<>();
            for (ProductPrice price : priceList) {
                priceIdList.add(price.getId());
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("mng_id", mngId);
            queryWrapper.in("price_id", priceIdList);
            List<ProductDiscount> list = list(queryWrapper);
            return list;
        }

        return null;
    }

    /**
     * 设置折扣
     * @param param
     * @return
     */
    public boolean saveOrUpdateDiscount(PrdDiscountParam param){
        List<ProductDiscount> list = param.getList();
        for (ProductDiscount discount : list) {
            discount.setCrteMngId(param.getCrteMngId());
            discount.setCrteTime(LocalDateTime.now());
            discount.setRemark("");
            this.saveOrUpdate(discount);
        }

        return true;
    }
}
